package com.yumeng.framework.persistence.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.yumeng.framework.persistence.mybatis.injector.MyAbstractMethod;
import com.yumeng.framework.persistence.mybatis.injector.MySqlMethod;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 逻辑删除
 * @author wxd
 * @date 2021/12/14 21:00
 */
public class LogicDeleteById extends MyAbstractMethod {

    private static final MySqlMethod SQL_METHOD = MySqlMethod.LOGIC_DELETE_BY_ID;

    public LogicDeleteById() {
        super(SQL_METHOD.getMethod());
    }

    /**
     * 注入自定义 MappedStatement
     * "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>"
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        if (!myHasLogicDelete(tableInfo)) return null;
        String sql;
 /*       List<TableFieldInfo> fieldInfos = tableInfo.getFieldList().stream()
                .filter(TableFieldInfo::isWithUpdateFill)
                .filter(f -> !f.isLogicDelete())
                .collect(toList());
        if (CollectionUtils.isNotEmpty(fieldInfos)) {
            String sqlSet = "SET " + SqlScriptUtils.convertIf(fieldInfos.stream()
                    .map(i -> i.getSqlSet(EMPTY)).collect(joining(EMPTY)), "!@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(_parameter.getClass())", true)
                    + myGetLogicDeleteSql(false, false);
            sql = String.format(SQL_METHOD.getSql(), tableInfo.getTableName(), sqlSet, tableInfo.getKeyColumn(),
                    tableInfo.getKeyProperty(), myGetLogicDeleteSql(true, true));
        } else {
            sql = String.format(SQL_METHOD.getSql(), tableInfo.getTableName(), mySqlLogicSet(tableInfo),
                    tableInfo.getKeyColumn(), tableInfo.getKeyProperty(),
                    myGetLogicDeleteSql(true, true));
        }*/
        //逻辑删除时，不考虑UpdateFill字段
        //UPDATE demo_test SET del_flag = 1, deler = #{deler}, del_time = #{delTime} WHERE test_id=#{id}  AND del_flag=0
        sql = String.format(SQL_METHOD.getSql(), tableInfo.getTableName(), mySqlLogicSet(tableInfo, null),
                tableInfo.getKeyColumn(), getMybatisPlusProperties().getCommKeyProp(),// CommKeyProp通用主键属性 用于不知道主键名称的场景，比如map传参  (正常情况使用tableInfo.getKeyProperty())
                myGetLogicDeleteSql(true, true, null));
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlSource);
    }

}
